const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../config/config');

/**
 * 认证中间件，用于验证 Token 是否合法
 * @param {Object} ctx - Koa context 对象
 * @param {Function} next - Koa next 函数
 */
const authMiddleware = async (ctx, next) => {
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    // 如果请求头中没有授权头信息，返回 401 Unauthorized
    ctx.status = 401;
    ctx.body = {
      error: 'Authorization header missing'
    };
    return;
  }

  const [type, token] = authorization.split(' ');
  if (type !== 'Bearer' || !token) {
    // 如果授权头信息格式不正确，返回 401 Unauthorized
    ctx.status = 401;
    ctx.body = {
      error: 'Invalid authorization header'
    };
    return;
  }

  try {
    const decodedToken = jwt.verify(token, jwtSecret);
    ctx.state.user = decodedToken;
    await next();
  } catch (err) {
    // 如果 Token 验证失败，返回 401 Unauthorized
    ctx.status = 401;
    ctx.body = {
      error: 'Invalid token'
    };
    return;
  }
};

module.exports = authMiddleware;
